package cn.tedu.egweibo3.controller;

import cn.tedu.egweibo3.common.response.JsonResult;
import cn.tedu.egweibo3.common.response.StatusCode;
import cn.tedu.egweibo3.mapper.UserMapper;
import cn.tedu.egweibo3.pojo.dto.UserLoginDto;
import cn.tedu.egweibo3.pojo.dto.UserRegDto;
import cn.tedu.egweibo3.pojo.entity.User;
import cn.tedu.egweibo3.pojo.vo.UserVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpSession;
import java.util.Date;

@Api(tags = "01.用户模块")
@Slf4j
@RestController
@RequestMapping("/v1/user/")
public class UserController {
    @Autowired
    private UserMapper userMapper;
    /**
     *1.注册模块
     */
    @PostMapping("reg")
    @ApiOperation(value = "注册功能")
    public JsonResult reg(@RequestBody UserRegDto userRegDto){
        log.debug("userRegDto"+userRegDto);
        UserVo userVo = userMapper.selectByUsername(userRegDto.getUsername());
        if (userVo != null) {
            return new JsonResult(StatusCode.USERNAME_ALREADY_EXISTS);
        }
        User user = new User();
        BeanUtils.copyProperties(userRegDto,user);
        user.setCreated(new Date());
        userMapper.insert(user);
        return JsonResult.ok();
    }
    /**
     * 2.登录功能
     */
    @PostMapping("login")
    @ApiOperation(value = "登录功能")
    public JsonResult login(@RequestBody UserLoginDto userLoginDto,@ApiIgnore HttpSession session){
        log.debug("UserLoginDto"+userLoginDto);
        UserVo userVo = userMapper.selectByUsername(userLoginDto.getUsername());
        if (userVo == null) {
            return new JsonResult(StatusCode.USERNAME_ERROR);
        }
        if (userVo.getPassword().equals(userLoginDto.getPassword())) {
            session.setAttribute("user",userVo);
            return new JsonResult(StatusCode.LOGIN_SUCCESS);
        }
        return new JsonResult(StatusCode.PASSWORD_ERROR);
    }
    /**
     * 3.获取当前用户
     */
    @GetMapping("currentUser")
    @ApiOperation(value = "获取当前用户功能")
    public JsonResult currentUser(@ApiIgnore HttpSession session){
        UserVo userVo = (UserVo) session.getAttribute("user");
        return JsonResult.ok(userVo);
    }
    /**
     * 4.退出登录功能
     */
    @GetMapping("logout")
    @ApiOperation(value = "退出登录功能")
    public void logout(@ApiIgnore HttpSession session){
        session.removeAttribute("user");
    }
}
